package com.small.nacos.naming.controllers;

import com.alibaba.nacos.api.exception.NacosException;
import com.small.nacos.core.distributed.distro.DistroProtocol;
import com.small.nacos.core.distributed.distro.entity.DistroKey;
import com.small.nacos.naming.consistency.Datum;
import com.small.nacos.naming.consistency.KeyBuilder;
import com.small.nacos.naming.consistency.ephemeral.distro.DistroHttpData;
import com.small.nacos.naming.core.Instances;
import com.small.nacos.naming.core.ServiceManager;
import com.small.nacos.naming.misc.SwitchDomain;
import com.small.nacos.naming.misc.UtilsAndCommons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Author zhoujin
 * @Date 2022/11/14 19:50
 */
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/distro")
public class DistroController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DistroController.class);

    @Autowired
    private DistroProtocol distroProtocol;

    @Autowired
    private ServiceManager serviceManager;

    @Autowired
    private SwitchDomain switchDomain;

    @PutMapping("/datum")
    public ResponseEntity onSyncDatum(@RequestBody Map<String, Datum<Instances>> dataMap) throws Exception {

        if (dataMap.isEmpty()) {
            LOGGER.error("[onSync] receive empty entity!");
            throw new NacosException(NacosException.INVALID_PARAM, "receive empty entity!");
        }
        for (Map.Entry<String, Datum<Instances>> entry : dataMap.entrySet()) {
            //判断是否是临时实例
            if (KeyBuilder.matchEphemeralKey(entry.getKey())) {
                String namespaceId = KeyBuilder.getNamespace(entry.getKey());
                String serviceName = KeyBuilder.getServiceName(entry.getKey());
                if (!serviceManager.containService(namespaceId, serviceName)) {
                    serviceManager.createEmptyService(namespaceId, serviceName, true);
                }

                DistroHttpData distroHttpData = new DistroHttpData(createDistroKey(entry.getKey()), entry.getValue());
                distroProtocol.onReceive(distroHttpData);
            }
        }
        return ResponseEntity.ok("ok");
    }


    private DistroKey createDistroKey(String resourceKey) {
        return new DistroKey(resourceKey, KeyBuilder.INSTANCE_LIST_KEY_PREFIX);
    }
}